package com.wd.serverconn;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.TrustManagerFactory;

public class SslServer {
	private ServerSocket socket;
	private String serverKeyStorePass = "111111";
	private String clientKeyStorePass = "111111";

	public void init() throws Exception {
		KeyManager[] keymanagers;
		SSLContext sslContext = null;
		KeyManagerFactory keyManager = null;
		sslContext = SSLContext.getInstance("TLS");
		keyManager = KeyManagerFactory.getInstance("SunX509");
		KeyStore serverKeyStroe = KeyStore.getInstance(KeyStore.getDefaultType());
		KeyStore clientKeyStore = KeyStore.getInstance(KeyStore
				.getDefaultType());
		
		serverKeyStroe.load(new FileInputStream(System.getProperty("user.dir")
				+ "\\assets\\" + "kserver.keystore"), "111111".toCharArray());

		keyManager.init(serverKeyStroe, serverKeyStorePass.toCharArray());
		keymanagers = keyManager.getKeyManagers();
		
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
		clientKeyStore.load(new FileInputStream(System.getProperty("user.dir")
				+ "\\assets\\" + "tserver.keystore"),
				clientKeyStorePass.toCharArray());
		tmf.init(clientKeyStore);
		
		sslContext.init(keymanagers, tmf.getTrustManagers(), null);

		socket = (SSLServerSocket) sslContext.getServerSocketFactory()
				.createServerSocket(9999); // .createSocket(field.getIp(),
		((SSLServerSocket)socket).setNeedClientAuth(true);
		while (true) {
			Socket server = socket.accept();
			createNewThread(server);
		}

	}

	private void createNewThread(final Socket server) {
		Thread thread = new Thread(){
			@Override
			public void run(){
				try {
					InputStream is = server.getInputStream();
					server.getOutputStream();
					byte [] bytes = new byte[1024];
					while(true){
						is.read(bytes);
						String s = new String(bytes);
						System.out.println(s);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		thread.start();
	}

}
